﻿// (c) Copyright Graeme Bradbury.
// graeme@siliconshark.com
// This source is subject to the Microsoft Permissive License.
// See http://www.microsoft.com/resources/sharedsource/licensingbasics/sharedsourcelicenses.mspx.
// All other rights reserved.

using System;
using System.Diagnostics;
using System.Windows;
using System.Windows.Data;
using System.Windows.Interactivity;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Shell;
using PanoramaTest;

namespace ConfApp.Infrastructure.Behaviours
{
    /// <summary>
    /// Behaviour that exposes a IsVisible property allowing binding between the ApplicationBar control and a ViewModel.
    /// </summary>
    public class BindableApplicationBarBehaviour : Behavior<PhoneApplicationPage>
    {
        public static readonly DependencyProperty IsVisibleProperty =
            DependencyProperty.Register("IsVisible", typeof(Binding), typeof(BindableApplicationBarBehaviour),
                                        new PropertyMetadata(null, HandleTargetIndexBindingChanged));

        private readonly BindingListener _listener;

        public BindableApplicationBarBehaviour()
        {
            _listener = new BindingListener(HandleBindingValueChanged);
        }

        public Binding IsVisible
        {
            get { return (Binding)this.GetValue(BindableApplicationBarBehaviour.IsVisibleProperty); }
            set { this.SetValue(BindableApplicationBarBehaviour.IsVisibleProperty, value); }
        }

        /// <summary>
        /// Handles the the source value changing
        /// </summary>
        private void HandleBindingValueChanged(Object sender, BindingChangedEventArgs args)
        {
            this.AssociatedObject.ApplicationBar.IsVisible = (bool)_listener.Value;
        }

        private static void HandleTargetIndexBindingChanged(DependencyObject sender,
                                                            DependencyPropertyChangedEventArgs args)
        {
            ((BindableApplicationBarBehaviour)sender).OnIsVisibleBindingChanged(args);
        }

        private void OnIsVisibleBindingChanged(DependencyPropertyChangedEventArgs args)
        {
            _listener.Binding = (Binding)args.NewValue;
        }

        protected override void OnAttached()
        {
            base.OnAttached();

            _listener.Element = AssociatedObject;
        }

        protected override void OnDetaching()
        {
            base.OnDetaching();
            _listener.Element = null;
        }
    }
}